// src/main/java/tech/aistar/controller/AfterSaleController.java
package tech.aistar.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import tech.aistar.pojo.AfterSale;
import tech.aistar.service.AfterSaleService;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/admin/after-sales")
public class AfterSaleController {

    @Autowired
    private AfterSaleService afterSaleService;

    /**
     * 获取售后列表（分页+搜索）
     * GET /api/admin/after-sales?orderId=xxx&buyerName=xxx&type=1&status=0&page=1&size=10
     */
    @GetMapping
    public Map<String, Object> getAfterSaleList(
            @RequestParam(required = false) String orderId,
            @RequestParam(required = false) String buyerName,
            @RequestParam(required = false) Integer type,
            @RequestParam(required = false) Integer status,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {

        List<AfterSale> afterSales = afterSaleService.getAfterSaleList(orderId, buyerName, type, status, page, size);
        Long total = afterSaleService.getAfterSaleCount(orderId, buyerName, type, status);

        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("data", afterSales);
        result.put("total", total);
        result.put("page", page);
        result.put("size", size);
        return result;
    }

    /**
     * 获取售后详情
     * GET /api/admin/after-sales/{id}
     */
    @GetMapping("/{id}")
    public Map<String, Object> getAfterSaleDetail(@PathVariable Integer id) {
        AfterSale afterSale = afterSaleService.getAfterSaleById(id);
        Map<String, Object> result = new HashMap<>();
        if (afterSale != null) {
            result.put("success", true);
            result.put("data", afterSale);
        } else {
            result.put("success", false);
            result.put("message", "售后记录不存在");
        }
        return result;
    }

    /**
     * 更新售后状态
     * PUT /api/admin/after-sales/{id}/status
     * 请求体: {"status": 1}
     */
    @PutMapping("/{id}/status")
    public Map<String, Object> updateAfterSaleStatus(@PathVariable Integer id, @RequestBody Map<String, Integer> request) {
        Integer status = request.get("status");
        boolean success = afterSaleService.updateAfterSaleStatus(id, status);
        Map<String, Object> result = new HashMap<>();
        result.put("success", success);
        if (status == 5) {
            result.put("message", success ? "售后已完成，记录已删除" : "操作失败");
        } else {
            result.put("message", success ? "状态更新成功" : "状态更新失败");
        }
        return result;
    }
}
